<template>
  <div>
    <el-form-item label="上传" prop="image">
      <el-button icon="el-icon-upload" type="primary" @click="selectFile()">{{text}}</el-button>
      <input  class="hidden" clearable type="file" ref="file"  @input="updateInput($event)" v-on:change="uploadFile ()" v-bind:id="inputId+'-input'"></input>
    </el-form-item>
  </div>
</template>

<script>
  export default {
    name: "file",
    props:{
      text:{
        default:"上传文件"
      },
      suffixs:{
        default: [],
      },
      inputId:{
        default: "file-upload",
      },
      afterUpload:{
        type:Function,
        default:null,
      }
    },
    data:function (){
      return{

      }
    },
    methods:{
      uploadFile(){
        let _this =this;
        let formData = new window.FormData();
        let file = _this.$refs.file.files[0];

        //判断文件格式
        let suffixs = _this.suffixs;
        let fileName = file.name;
        let suffix = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length).toLowerCase();
        let validateSuffix = false;
        for( let i = 0; i<suffixs.length;i++ ){
          if(suffixs[i].toLowerCase() === suffix){
            validateSuffix = true;
            break;
          }
        }
        if (!validateSuffix){
          _this.$message.error('文件格式不正确,只支持'+suffixs.join(","));
          $("#"+_this.inputId+"-input").val("");
          return;
        }
        formData.append('file',file);
        console.log("图片",formData);
        _this.$ajax.post(process.env.VUE_APP_SERVER+'/file/admin/upload',formData).then((response)=>{
          let resp = response.data;

          console.log("上传文件成功:",resp);
          _this.afterUpload(resp);
          $("#"+_this.inputId+"-input").val("");
        })
      },
      selectFile(){
        let _this = this;
        $("#" + _this.inputId + "-input").trigger("click");
      },
      //更新键盘输入input值
      updateInput(e){
        let _this = this;
        _this.$forceUpdate()
      },
    }
  }
</script>